/**
 * 朋知云学平台主要JavaScript文件
 * 包含通用功能和工具函数
 */

// DOM加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 初始化导航栏
    initNavigation();
    
    // 初始化通知系统
    initNotifications();
    
    // 检查用户登录状态
    checkLoginStatus();
});

/**
 * 初始化导航栏
 */
function initNavigation() {
    // 获取当前页面路径
    const currentPath = window.location.pathname.split('/').pop() || 'index.html';
    
    // 设置当前页面的导航链接为激活状态
    const navLinks = document.querySelectorAll('.nav-menu a');
    navLinks.forEach(link => {
        const linkPath = link.getAttribute('href');
        if (linkPath === currentPath) {
            link.classList.add('active');
        } else {
            link.classList.remove('active');
        }
    });
}

/**
 * 初始化通知系统
 */
function initNotifications() {
    // 创建通知容器
    if (!document.querySelector('.notification-container')) {
        const container = document.createElement('div');
        container.className = 'notification-container';
        document.body.appendChild(container);
    }
}

/**
 * 显示通知
 * @param {string} message - 通知消息
 * @param {string} type - 通知类型 (success, error, warning, info)
 * @param {number} duration - 显示时长(毫秒)
 */
function showNotification(message, type = 'info', duration = 3000) {
    const container = document.querySelector('.notification-container');
    
    // 创建通知元素
    const notification = document.createElement('div');
    notification.className = `notification notification-${type}`;
    
    // 设置通知内容
    notification.innerHTML = `
        <div class="notification-content">${message}</div>
        <button class="notification-close">&times;</button>
    `;
    
    // 添加到容器
    container.appendChild(notification);
    
    // 显示通知
    setTimeout(() => {
        notification.classList.add('show');
    }, 10);
    
    // 关闭按钮事件
    const closeBtn = notification.querySelector('.notification-close');
    closeBtn.addEventListener('click', () => {
        closeNotification(notification);
    });
    
    // 自动关闭
    if (duration > 0) {
        setTimeout(() => {
            closeNotification(notification);
        }, duration);
    }
}

/**
 * 关闭通知
 * @param {HTMLElement} notification - 通知元素
 */
function closeNotification(notification) {
    notification.classList.remove('show');
    
    // 动画结束后移除元素
    setTimeout(() => {
        if (notification.parentElement) {
            notification.parentElement.removeChild(notification);
        }
    }, 300);
}

/**
 * 检查用户登录状态
 */
function checkLoginStatus() {
    // 从localStorage获取用户信息
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || 'null');
    
    // 更新导航栏显示
    updateNavigation(userInfo);
    
    return userInfo;
}

/**
 * 更新导航栏显示
 * @param {Object|null} userInfo - 用户信息
 */
function updateNavigation(userInfo) {
    const userActions = document.querySelector('.user-actions');
    
    if (!userActions) return;
    
    if (userInfo) {
        // 用户已登录
        userActions.innerHTML = `
            <div class="user-dropdown">
                <div class="user-dropdown-toggle">
                    <div class="user-info-wrapper">
                        <div class="user-text">
                            <span class="username">${userInfo.username}</span>
                            ${userInfo.isAdmin ? '<span class="role-badge role-admin"><i class="icon-crown"></i>管理员</span>' : ''}
                        </div>
                        <i class="dropdown-arrow"></i>
                    </div>
                </div>
                <div class="user-dropdown-menu">
                    <a href="user-center.html" class="dropdown-item"><i class="icon-user"></i>个人中心</a>
                    ${userInfo.isAdmin ? '<a href="admin/dashboard.html" class="dropdown-item"><i class="icon-settings"></i>管理后台</a>' : ''}
                    <a href="#" id="logout-btn" class="dropdown-item logout-item"><i class="icon-logout"></i>退出登录</a>
                </div>
            </div>
        `;
        
        // 添加退出登录事件
        const logoutBtn = document.getElementById('logout-btn');
        if (logoutBtn) {
            logoutBtn.addEventListener('click', function(e) {
                e.preventDefault();
                logout();
            });
        }
        
        // 添加下拉菜单切换
        const dropdownToggle = document.querySelector('.user-dropdown-toggle');
        if (dropdownToggle) {
            dropdownToggle.addEventListener('click', function() {
                const dropdownMenu = document.querySelector('.user-dropdown-menu');
                dropdownMenu.classList.toggle('show');
            });
        }
    } else {
        // 用户未登录
        userActions.innerHTML = `
            <a href="login.html" class="btn btn-login">登录</a>
            <a href="register.html" class="btn btn-register">注册</a>
        `;
    }
}

/**
 * 用户登录
 * @param {string} username - 用户名
 * @param {string} password - 密码
 * @returns {Promise<Object>} - 登录结果
 */
async function login(username, password) {
    // 模拟登录请求
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            // 模拟用户数据
            const users = [
                { id: 1, username: 'admin', password: 'admin123', isAdmin: true, avatar: '../static/avatar1.png' },
                { id: 2, username: 'user', password: 'user123', isAdmin: false, avatar: '../static/avatar-default.png' }
            ];
            
            // 查找用户
            const user = users.find(u => u.username === username && u.password === password);
            
            if (user) {
                // 登录成功，存储用户信息（不包含密码）
                const { password, ...userInfo } = user;
                localStorage.setItem('userInfo', JSON.stringify(userInfo));
                
                // 更新导航栏
                updateNavigation(userInfo);
                
                resolve({ success: true, user: userInfo });
            } else {
                reject({ success: false, message: '用户名或密码错误' });
            }
        }, 1000);
    });
}

/**
 * 用户注册
 * @param {Object} userData - 用户数据
 * @returns {Promise<Object>} - 注册结果
 */
async function register(userData) {
    // 模拟注册请求
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            // 模拟注册成功
            const newUser = {
                id: Date.now(),
                username: userData.username,
                isAdmin: false,
                avatar: '../static/avatar-default.png'
            };
            
            // 存储用户信息
            localStorage.setItem('userInfo', JSON.stringify(newUser));
            
            // 更新导航栏
            updateNavigation(newUser);
            
            resolve({ success: true, user: newUser });
        }, 1000);
    });
}

/**
 * 用户退出登录
 */
function logout() {
    // 清除用户信息
    localStorage.removeItem('userInfo');
    
    // 更新导航栏
    updateNavigation(null);
    
    // 显示通知
    showNotification('您已成功退出登录', 'success');
    
    // 跳转到首页
    window.location.href = 'index.html';
}

/**
 * 格式化日期
 * @param {string|Date} date - 日期对象或日期字符串
 * @param {string} format - 格式化模板
 * @returns {string} - 格式化后的日期字符串
 */
function formatDate(date, format = 'YYYY-MM-DD') {
    const d = new Date(date);
    
    const year = d.getFullYear();
    const month = String(d.getMonth() + 1).padStart(2, '0');
    const day = String(d.getDate()).padStart(2, '0');
    const hours = String(d.getHours()).padStart(2, '0');
    const minutes = String(d.getMinutes()).padStart(2, '0');
    const seconds = String(d.getSeconds()).padStart(2, '0');
    
    return format
        .replace('YYYY', year)
        .replace('MM', month)
        .replace('DD', day)
        .replace('HH', hours)
        .replace('mm', minutes)
        .replace('ss', seconds);
}

/**
 * 获取URL参数
 * @param {string} name - 参数名
 * @returns {string|null} - 参数值
 */
function getUrlParam(name) {
    const urlParams = new URLSearchParams(window.location.search);
    return urlParams.get(name);
}

/**
 * 创建分页元素
 * @param {number} currentPage - 当前页码
 * @param {number} totalPages - 总页数
 * @param {Function} onPageChange - 页码变化回调
 * @returns {HTMLElement} - 分页DOM元素
 */
function createPagination(currentPage, totalPages, onPageChange) {
    const pagination = document.createElement('div');
    pagination.className = 'pagination';
    
    // 上一页
    if (currentPage > 1) {
        const prevItem = document.createElement('div');
        prevItem.className = 'pagination-item';
        const prevLink = document.createElement('a');
        prevLink.className = 'pagination-link';
        prevLink.href = '#';
        prevLink.textContent = '上一页';
        prevLink.addEventListener('click', (e) => {
            e.preventDefault();
            onPageChange(currentPage - 1);
        });
        prevItem.appendChild(prevLink);
        pagination.appendChild(prevItem);
    }
    
    // 页码
    for (let i = 1; i <= totalPages; i++) {
        // 显示当前页附近的页码
        if (
            i === 1 || // 第一页
            i === totalPages || // 最后一页
            (i >= currentPage - 2 && i <= currentPage + 2) // 当前页附近
        ) {
            const pageItem = document.createElement('div');
            pageItem.className = 'pagination-item';
            const pageLink = document.createElement('a');
            pageLink.className = 'pagination-link';
            if (i === currentPage) {
                pageLink.classList.add('active');
            }
            pageLink.href = '#';
            pageLink.textContent = i;
            pageLink.addEventListener('click', (e) => {
                e.preventDefault();
                onPageChange(i);
            });
            pageItem.appendChild(pageLink);
            pagination.appendChild(pageItem);
        } else if (
            (i === currentPage - 3 && currentPage > 3) ||
            (i === currentPage + 3 && currentPage < totalPages - 2)
        ) {
            // 显示省略号
            const ellipsisItem = document.createElement('div');
            ellipsisItem.className = 'pagination-item';
            ellipsisItem.textContent = '...';
            pagination.appendChild(ellipsisItem);
        }
    }
    
    // 下一页
    if (currentPage < totalPages) {
        const nextItem = document.createElement('div');
        nextItem.className = 'pagination-item';
        const nextLink = document.createElement('a');
        nextLink.className = 'pagination-link';
        nextLink.href = '#';
        nextLink.textContent = '下一页';
        nextLink.addEventListener('click', (e) => {
            e.preventDefault();
            onPageChange(currentPage + 1);
        });
        nextItem.appendChild(nextLink);
        pagination.appendChild(nextItem);
    }
    
    return pagination;
}

/**
 * 防抖函数
 * @param {Function} func - 要执行的函数
 * @param {number} delay - 延迟时间(毫秒)
 * @returns {Function} - 防抖处理后的函数
 */
function debounce(func, delay = 300) {
    let timer = null;
    return function(...args) {
        if (timer) clearTimeout(timer);
        timer = setTimeout(() => {
            func.apply(this, args);
        }, delay);
    };
}

/**
 * 节流函数
 * @param {Function} func - 要执行的函数
 * @param {number} limit - 时间限制(毫秒)
 * @returns {Function} - 节流处理后的函数
 */
function throttle(func, limit = 300) {
    let inThrottle = false;
    return function(...args) {
        if (!inThrottle) {
            func.apply(this, args);
            inThrottle = true;
            setTimeout(() => {
                inThrottle = false;
            }, limit);
        }
    };
}

/**
 * 验证表单字段
 * @param {string} value - 字段值
 * @param {string} type - 验证类型
 * @returns {boolean} - 验证结果
 */
function validateField(value, type) {
    switch (type) {
        case 'email':
            return /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(value);
        case 'phone':
            return /^1[3-9]\d{9}$/.test(value);
        case 'password':
            return value.length >= 6;
        case 'username':
            return value.length >= 3 && value.length <= 20;
        case 'required':
            return value.trim() !== '';
        default:
            return true;
    }
}

/**
 * 创建模态框
 * @param {Object} options - 模态框配置
 * @returns {Object} - 模态框对象
 */
function createModal(options = {}) {
    const defaults = {
        title: '提示',
        content: '',
        confirmText: '确定',
        cancelText: '取消',
        showCancel: true,
        onConfirm: null,
        onCancel: null,
        onClose: null
    };
    
    const settings = { ...defaults, ...options };
    
    // 创建模态框元素
    const modal = document.createElement('div');
    modal.className = 'modal';
    
    // 设置模态框内容
    modal.innerHTML = `
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title">${settings.title}</h3>
                <button class="modal-close">&times;</button>
            </div>
            <div class="modal-body">${settings.content}</div>
            <div class="modal-footer">
                ${settings.showCancel ? `<button class="btn btn-secondary modal-cancel">${settings.cancelText}</button>` : ''}
                <button class="btn btn-primary modal-confirm">${settings.confirmText}</button>
            </div>
        </div>
    `;
    
    // 添加到文档
    document.body.appendChild(modal);
    
    // 显示模态框
    setTimeout(() => {
        modal.classList.add('show');
    }, 10);
    
    // 关闭模态框函数
    const closeModal = () => {
        modal.classList.remove('show');
        setTimeout(() => {
            if (modal.parentElement) {
                modal.parentElement.removeChild(modal);
            }
        }, 300);
    };
    
    // 绑定事件
    const closeBtn = modal.querySelector('.modal-close');
    closeBtn.addEventListener('click', () => {
        if (typeof settings.onClose === 'function') {
            settings.onClose();
        }
        closeModal();
    });
    
    const confirmBtn = modal.querySelector('.modal-confirm');
    confirmBtn.addEventListener('click', () => {
        if (typeof settings.onConfirm === 'function') {
            settings.onConfirm();
        }
        closeModal();
    });
    
    if (settings.showCancel) {
        const cancelBtn = modal.querySelector('.modal-cancel');
        cancelBtn.addEventListener('click', () => {
            if (typeof settings.onCancel === 'function') {
                settings.onCancel();
            }
            closeModal();
        });
    }
    
    // 返回模态框对象
    return {
        element: modal,
        close: closeModal
    };
}

/**
 * 显示确认对话框
 * @param {string} message - 提示消息
 * @param {Function} onConfirm - 确认回调
 * @param {Function} onCancel - 取消回调
 */
function showConfirm(message, onConfirm, onCancel) {
    createModal({
        title: '确认',
        content: message,
        onConfirm,
        onCancel
    });
}

/**
 * 显示提示对话框
 * @param {string} message - 提示消息
 * @param {Function} onClose - 关闭回调
 */
function showAlert(message, onClose) {
    createModal({
        title: '提示',
        content: message,
        showCancel: false,
        onConfirm: onClose,
        onClose
    });
}

/**
 * 加载数据
 * @param {string} url - 请求URL
 * @param {Object} options - 请求选项
 * @returns {Promise<Object>} - 请求结果
 */
async function fetchData(url, options = {}) {
    try {
        // 模拟API请求
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                // 根据URL返回不同的模拟数据
                if (url.includes('demands')) {
                    resolve({
                        success: true,
                        data: [
                            {
                                id: 1,
                                title: '山区小学语文教师支教',
                                location: '云南省丽江市',
                                startDate: '2023-10-01',
                                endDate: '2023-12-31',
                                subjects: ['语文', '数学'],
                                isUrgent: true
                            },
                            {
                                id: 2,
                                title: '乡村初中英语教师招募',
                                location: '贵州省黔东南州',
                                startDate: '2023-09-15',
                                endDate: '2024-01-15',
                                subjects: ['英语'],
                                isUrgent: true
                            },
                            {
                                id: 3,
                                title: '留守儿童课后辅导',
                                location: '四川省凉山州',
                                startDate: '2023-10-10',
                                endDate: '2023-12-20',
                                subjects: ['综合课程'],
                                isUrgent: true
                            }
                        ]
                    });
                } else if (url.includes('applications')) {
                    resolve({
                        success: true,
                        data: [
                            {
                                id: 1,
                                demandId: 1,
                                demandTitle: '山区小学语文教师支教',
                                applyDate: '2023-09-05',
                                status: 'pending'
                            },
                            {
                                id: 2,
                                demandId: 2,
                                demandTitle: '乡村初中英语教师招募',
                                applyDate: '2023-09-10',
                                status: 'approved'
                            }
                        ]
                    });
                } else {
                    reject({ success: false, message: '未知请求' });
                }
            }, 500);
        });
    } catch (error) {
        console.error('请求失败:', error);
        throw error;
    }
}

// 导出工具函数
window.utils = {
    showNotification,
    formatDate,
    getUrlParam,
    createPagination,
    debounce,
    throttle,
    validateField,
    showConfirm,
    showAlert,
    fetchData
};

// 导出用户相关函数
window.userService = {
    login,
    register,
    logout,
    checkLoginStatus
};